import { useState } from "react";
import { useDispatch } from "react-redux";
import { Input, message } from "antd";
import { EditOutlined, CheckOutlined, CloseOutlined } from "@ant-design/icons";

import { updateUserInfoAsync } from "../redux/userSlice";
import styles from "../css/PersonalInfoItem.module.css";

function PersonalInfoItem(props) {
  const [isEdit, setIsEdit] = useState(false);
  const [value, setValue] = useState(props.info.itemValue);
  const dispatch = useDispatch();

  async function handleEdit(key, value) {
    if (value.trim()) {
      // 派发异步 action
      dispatch(
        updateUserInfoAsync({
          userId: props.info.userId,
          newInfo: {
            [key]: value,
          },
        })
      );
      setIsEdit(false);
      message.success("修改成功");
    } else {
      message.error("昵称不能为空");
    }
  }

  return (
    <div className={styles.infoContainer}>
      <div className={styles.left}>
        <div>{props.info.itemName}：</div>
        <div>
          {props.editable ? (
            <>
              {isEdit ? (
                <span style={{ display: "flex", alignItems: "center" }}>
                  <Input
                    size="small"
                    defaultValue={props.info.itemValue}
                    onChange={(e) => setValue(e.target.value)}
                  />
                  &nbsp;
                  <CheckOutlined
                    className={styles.clickable}
                    onClick={() => handleEdit(props.info.itemKey, value)}
                  />
                  &nbsp;
                  <CloseOutlined
                    className={styles.clickable}
                    onClick={() => setIsEdit(false)}
                  />
                </span>
              ) : (
                <>
                  {props.info.itemValue}
                  &nbsp;
                  <EditOutlined
                    className={styles.clickable}
                    onClick={() => setIsEdit(true)}
                  />
                </>
              )}
            </>
          ) : (
            // 不可编辑直接展示数据
            <>{props.info.itemValue}</>
          )}
        </div>
      </div>
    </div>
  );
}

export default PersonalInfoItem;
